import gtk
from os.path import exists
from dataPreview import MatrixPreview
from symbide.src.extensions.numpy.additionalFunctions import load_csv
            

class DataLoader(gtk.Window):
    def __init__(self, mainWindow):
        gtk.Window.__init__(self)

        self.set_default_size(400,100)
        self.set_transient_for(mainWindow)
        self.set_title('Symbide - Import data')
        self.set_destroy_with_parent(True)
        self.show()
        
        self.mainWindow = mainWindow
        
        main_vbox=gtk.VBox()
        main_vbox.show()
        
        top_hbox=gtk.HBox()
        top_hbox.show()
        main_vbox.pack_start(top_hbox)
        
        self.dataSettings = DataSettings(self)
        top_hbox.pack_start(self.dataSettings, expand=True)  
        
        self.dataView = DataView()
        self.dataView.hide_all()
        top_hbox.pack_start(self.dataView,expand=True, padding=20)
        
        self.actionBar = ActionBar(self)
        main_vbox.pack_start(self.actionBar, expand=False)
        
        self.add(main_vbox)

class ActionBar(gtk.HBox):
    def __init__(self, ancestor):
        gtk.HBox.__init__(self)
        self.show()
        
        self.ancestor = ancestor
        
        b0 = gtk.Button(stock=gtk.STOCK_PASTE)
        b0.connect('clicked', self._event_paste)
        b0.show()
        
        b1 = gtk.Button(stock=gtk.STOCK_CLOSE)
        b1.connect('clicked', self._event_close)
        b1.show()
        
        l = gtk.Label('')
        l.show()
        
        self.pack_start(l)
        self.pack_start(b0, expand=False)
        self.pack_start(b1, expand=False)
        
    def _event_close(self, *args):
        self.ancestor.destroy()
        
    def _event_paste(self, *args):
        d = self.ancestor.dataSettings
        path = "%s"%d.fileChooser.get_preview_filename()
        q = []
        for i, j in ((0, 'hsplit'), (1, 'vsplit'), (3, 'row_filter'), (4, 'col_filter')):
            buf = d.queries[i].get_text()
            if buf:
                q.append('%s="%s"'%(j,buf))
        
        command = 'load_csv(path="%s", %s)'%(path, ', '.join(q))
        self.ancestor.mainWindow.children[0].notebook.insertText(command)

class DataSettings(gtk.VBox):
    def __init__(self, ancestor):
        gtk.VBox.__init__(self)
        
        self.show()
        self.ancestor = ancestor
        
        self.fileChooser = gtk.FileChooserButton('Select a File')
        self.fileChooser.connect('selection-changed', self.view)
        self.fileChooser.show()
        
        expander = gtk.Expander()
        expander.show()
        
        table = gtk.Table(rows=5, columns=2)
        table.show()
        
        labels = ('Horizontal Deliminator:',
                  'Vertical Deliminator:',
                  '',
                  'Used rows:',
                  'Used columns:',)
        
        self.queries = (gtk.Entry(),
                        gtk.Entry(),
                        gtk.Label(''),
                        gtk.Entry(),
                        gtk.Entry())

        for i in range(len(labels)):
            hbox = gtk.HBox()
            hbox.show()
            l = gtk.Label(labels[i])
            l.show()
            p = gtk.Label('')
            p.show()
            hbox.pack_start(l, expand=False)
            hbox.pack_start(p)
            
            self.queries[i].show()
            self.queries[i].connect('key-press-event', self._event_key_press)
            table.attach(hbox,0, 1, i, i+1, gtk.FILL, 0, ypadding=4)
            table.attach(self.queries[i],1, 2, i, i+1, yoptions=0)
        
        expander.add(table)
        
        l = gtk.Label('')
        l.show()
        self.pack_end(l)
        
        self.checkButton_preview = gtk.CheckButton('Show Preview')
        self.checkButton_preview.connect('toggled', self.view)
        self.checkButton_preview.show()
        
        self.checkButton_source = gtk.CheckButton('Show Source')
        self.checkButton_source.connect('toggled', self.view)
        self.checkButton_source.show()
        
        self.pack_start(self.fileChooser, expand=False)
        self.pack_start(expander, expand=False)
        self.pack_start(self.checkButton_source, expand=False)
        self.pack_start(self.checkButton_preview, expand=False)
        
    def _event_key_press(self, widget, event):
        keyval, modifier = gtk.accelerator_parse('Return')
        if event.keyval==keyval:
            self.view()
        
    def view(self, *args):
        path = self.fileChooser.get_preview_filename()
        if not path or not exists(path):
            self.ancestor.dataView.hide_all()
            return
            
        if self.checkButton_source.get_active():
            f = open(path, 'r')
            buf = f.read()
            f.close()
            self.ancestor.dataView.buffer.set_text(buf)
            self.ancestor.dataView.source.show_all()
            self.ancestor.dataView.show()
        else:
            self.ancestor.dataView.source.hide_all()
        
        if self.checkButton_preview.get_active():
            hdel = self.queries[0].get_text()
            vdel = self.queries[1].get_text()
            rows = self.queries[3].get_text()
            cols = self.queries[4].get_text()
            m=load_csv(path, hdel, vdel, rows, cols)
            self.ancestor.dataView.matrixPreview.preview(m)
            self.ancestor.dataView.preview.show_all()
            self.ancestor.dataView.show()
        else:
            self.ancestor.dataView.preview.hide_all()
        
        
class DataView(gtk.VBox):
    def __init__(self):
        gtk.VBox.__init__(self)
        self.show()
        
        self.source = gtk.VBox()
        self.source.show()
        self.pack_start(self.source)
        
        self.preview = gtk.VBox()
        self.preview.show()
        self.pack_start(self.preview)
        
        l0 = gtk.Label('Source')
        l0.show()
        self.source.pack_start(l0, expand=False, padding=15)
        
        sw0 = gtk.ScrolledWindow()
        sw0.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
        sw0.show()
        self.source.pack_start(sw0)
        
        self.buffer = gtk.TextBuffer()
        tv = gtk.TextView(self.buffer)
        tv.show()
        sw0.add_with_viewport(tv)
        
        l1 = gtk.Label('Preview')
        l1.show()
        self.preview.pack_start(l1, expand=False, padding=15)
        
        sw1 = gtk.ScrolledWindow()
        sw1.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
        sw1.show()
        self.preview.pack_start(sw1)
        
        self.matrixPreview = MatrixPreview()
        sw1.add_with_viewport(self.matrixPreview)
        
    def preview(self, matrix):
        self.matrixPreview.preview(matrix)